﻿using com.fmtx.IDal;
using com.fmtx.Model;
using fmtx.Framework.DALFactory;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using fmtx.Utility;

namespace website.Areas.Action.Controllers
{
    public class PictureController : BaseController
    {
        //
        // GET: /Action/Picture/
        private IPictureType pictureType = DataAccess<IPictureType>.GetObject();
        private IPicture picture = DataAccess<IPicture>.GetObject();

        #region 简单查询
        /// <summary>
        /// 简单查询
        /// </summary>
        /// <param name="maxid"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public ActionResult GetPicture(int maxid, int size, string keyword)
        {
            var list = PictureCache.Query(maxid, size, keyword);
            return Json(list, JsonRequestBehavior.AllowGet);
        } 
        #endregion

        #region 简单查询
        /// <summary>
        /// 简单查询
        /// </summary>
        /// <param name="maxid"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [OutputCache(Duration = 10)]
        public ActionResult GetHostPicture(int index, int size, string title, string keyword)
        {
            var list = picture.QureyHost(index, size, title, keyword);
            var res = new List<OutPut>();
            foreach (var item in list)
            {
                res.Add(PictureCache.BindDetail(item));
            }
            return Json(res, JsonRequestBehavior.AllowGet);
        } 
        #endregion

        #region 简单查询
        /// <summary>
        /// 简单查询
        /// </summary>
        /// <param name="maxid"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [OutputCache(Duration = 10)]
        public ActionResult GetPraisePicture(int index, int size, string title, string keyword)
        {
            var list = picture.QureyPraise(index, size, title, keyword);
            var res = new List<OutPut>();
            foreach (var item in list)
            {
                res.Add(PictureCache.BindDetail(item));
            }
            return Json(res, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 保存图片类型
        /// <summary>
        /// 保存图片类型
        /// </summary>
        /// <param name="name"></param>
        /// <param name="jsoncallback"></param>
        /// <returns></returns>
        [ApiIsLogin]
        public JavaScriptResult AddType(string name, string jsoncallback)
        {
            Hashtable hash = new Hashtable();
            try
            {
                if (!string.IsNullOrEmpty(name))
                {
                    PictureType model = new PictureType();
                    model.Uid = userInfo.Uid;
                    model.Name = name.FileDirt();

                    pictureType.Add(model);

                    hash["error"] = 0;
                    hash["id"] = model.Id;
                }
                else
                {
                    hash["error"] = 1;
                    hash["msg"] = "请输入内容！";
                }
            }
            catch (Exception ex)
            {
                fmtx.Framework.Log.Error(ex);
                hash["error"] = 1;
                hash["msg"] = "操作失败！" + ex.Message;
            }
            return JavaScript(jsoncallback + "(" + JsonConvert.SerializeObject(hash) + ")");
        } 
        #endregion

        #region 上传临时文件
        /// <summary>
        /// 上传临时文件
        /// </summary>
        /// <param name="fileToUpload"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Upload(string qqfile, int? width)
        {
            if (userInfo.Uid == 0)
            {
                return Json(new { error = "请登录" }, "text/html");
            }
            if (!ConfigurationManager.AppSettings["FileExtension"].Contains(Path.GetExtension(qqfile).Substring(1).ToLower()))
                return Json(new { error = "非法文件！" }, "text/html");
            string uploadFolder = string.Format(StaticCs.VirtualPath + userInfo.Uid + "/", userInfo.Uid);
            string path = Server.MapPath("~" + uploadFolder);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string guid = Guid.NewGuid().ToString().Replace("-", "");
            string extname = Path.GetExtension(qqfile);
            string filename = guid + extname;
            try
            {
                Stream stream = Request.Files.Count > 0
                    ? Request.Files[0].InputStream
                    : Request.InputStream;
                string filePath = Path.Combine(path, filename);
                if (width != null)
                {
                    StaticCs.SaveAsImg(stream, path, filename, width.Value, 400);
                }
                else
                {
                    var buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    System.IO.File.WriteAllBytes(filePath, buffer);
                }
                return Json(new { success = true, name = filename, pic = uploadFolder + filename }, "text/html");

            }
            catch (Exception ex)
            {
                return Json(new { error = ex.Message }, "text/html");
            }
        }
        #endregion

        #region 设为封面
        /// <summary>
        /// 设为封面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [IsLoginJson]
        public ActionResult SetFrontCover(int id)
        {
            var pic = picture.Get(id);
            if (userInfo.Uid != pic.Uid)
            {
                return Json(new { success = false }, JsonRequestBehavior.AllowGet);
            }
            var type = pictureType.Get(pic.TypeId);
            type.FrontCover = pic.PicAddress;
            return Json(new { success = pictureType.Update(type),pic=pic.PicAddress },JsonRequestBehavior.AllowGet);
        } 
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [IsLoginJson]
        [HttpPost]
        public ActionResult DelPictrue(int id)
        {
            Hashtable hash = new Hashtable();
            var pic = picture.Get(id);
            if (pic.Uid != userInfo.Uid&&!IsManager)
            {
                hash["error"] = 1001;
            }
            else
            {
                try
                {
                    picture.Delete(id);
                    PictureCache.Remove(id);
                    hash["error"] = 0;
                }
                catch (Exception ex)
                {
                    hash["error"] = 1;
                    fmtx.Framework.Log.Error(ex);
                }
            }
            return Json(hash);
        } 
        #endregion

        #region 删除相册
        /// <summary>
        /// 删除相册
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [IsLoginJson]
        [HttpPost]
        public ActionResult DelPictrueType(int id)
        {
            Hashtable hash = new Hashtable();
            var type = pictureType.Get(id);
            if (type.Uid != userInfo.Uid&&!IsManager)
            {
                hash["error"] = 1001;
            }
            else
            {
                try
                {
                    pictureType.Delete(id);
                    PictureCache.RemoveType(id);
                    hash["error"] = 0;
                }
                catch (Exception ex)
                {
                    hash["error"] = 1;
                    fmtx.Framework.Log.Error(ex);
                }
            }
            return Json(hash);
        } 
        #endregion

        #region 保存图片信息
        /// <summary>
        /// 保存图片信息
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [IsLoginJson]
        public ActionResult EditPicture(string title, string content, int id)
        {
            Hashtable hash = new Hashtable();
            var model = picture.Get(id);
            if (model.Uid != userInfo.Uid&&!IsManager)
            {
                hash["error"] = 1001;
            }
            else
            {
                model.Title = title.FileDirt();
                model.Content = content.FileDirt();
                picture.Update(model);
                PictureCache.Update(model);
                hash["error"] = 0;
            }
            return Json(hash);
        } 
        #endregion
    }
}
